/*
 * @(#)PIMDemo.java	1.3 04/03/22
 *
 * Copyright (c) 2000-2004 Sun Microsystems, Inc. All rights reserved.
 * PROPRIETARY/CONFIDENTIAL
 * Use is subject to license terms
 */

package example.pim;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;

/**
 * Demonstrate the use of JSR 75 PIM APIs
 */
public class PIMDemo extends MIDlet {
    public String guser = "";
    public String gpass = "";
    private String url = "http://sharifgae.appspot.com/contacts";//"http://localhost:8080/contacts";//
    
    public void startApp() {
        Display.getDisplay(this).setCurrent(new ListTypeSelectionScreen(this));
    }
    
    protected void destroyApp(boolean param) { }
    
    protected void pauseApp() { }
    
    void exit() {
        destroyApp(false);
        notifyDestroyed();
    }
    
    void reportException(Exception e, Displayable d) {
        Alert alert = new Alert("Error", e.getMessage(), null, AlertType.ERROR);
        alert.setTimeout(Alert.FOREVER);
        Display.getDisplay(this).setCurrent(alert, d);
        e.printStackTrace();
    }
    
    public String sendHttpPost(String param) {
        HttpConnection hcon = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;
        StringBuffer res = new StringBuffer();
        
        try {
            hcon = (HttpConnection) Connector.open(this.url, Connector.READ_WRITE);
            hcon.setRequestMethod(HttpsConnection.POST);
            
            dos = hcon.openDataOutputStream();
            byte[] rbody = param.getBytes();
            //dos.write(rbody);
            for( int i = 0; i < rbody.length; i++ ) {
                dos.writeByte(rbody[i]);
            }
            
            
            //dos.flush();
            
            dis = new DataInputStream( hcon.openInputStream() );
            int ch;
            while( (ch = dis.read()) != -1 ){
                res.append((char)ch);
            }
            
        }catch( Exception e ){
            e.printStackTrace();
        } finally {
            try {
                if( hcon != null ) hcon.close();
                if( dis != null ) dis.close();
                if( dos != null ) dos.close();
            } catch( Exception e ) {
                e.printStackTrace();
            }
        }
        return res.toString();
    }
}
